import { get, post, put, del } from '../utils/request';
import { ApiResponse, User, Torrent, PageResult, AdminStats, InvitationCode } from '../types';
import request from '../utils/request';

/**
 * 获取用户列表
 */
export function getUsers(params?: {
  page?: number;
  size?: number;
  keyword?: string;
}) {
  return get<ApiResponse<PageResult<User>>>('/admin/users', params);
}

/**
 * 修改用户等级
 */
export function updateUserClass(userId: number, userClass: number) {
  return put<ApiResponse<null>>(`/admin/users/${userId}/class?userClass=${userClass}`);
}

/**
 * 修改用户状态
 */
export function updateUserStatus(userId: number, status: number) {
  return put<ApiResponse<null>>(`/admin/users/${userId}/status?status=${status}`);
}

/**
 * 获取待审核种子
 */
export function getPendingTorrents() {
  return get<ApiResponse<PageResult<Torrent>>>('/admin/torrents/pending');
}

/**
 * 审核通过种子
 */
export function approveTorrent(torrentId: number) {
  return put<ApiResponse<null>>(`/admin/torrents/${torrentId}/approve`);
}

/**
 * 拒绝种子
 */
export function rejectTorrent(torrentId: number, reason: string) {
  return put<ApiResponse<null>>(`/admin/torrents/${torrentId}/reject`, { reason });
}

/**
 * 创建邀请码
 */
export function createInvitation() {
  return post<ApiResponse<InvitationCode>>('/admin/invitations/create');
}

/**
 * 批量创建邀请码
 */
export function batchCreateInvitations(count: number) {
  return post<ApiResponse<InvitationCode[]>>('/admin/invitations/batch', { count });
}

/**
 * 获取邀请码列表
 */
export function getInvitations(params?: {
  page?: number;
  size?: number;
}) {
  return get<ApiResponse<PageResult<InvitationCode>>>('/admin/invitations', params);
}

/**
 * 删除邀请码
 */
export function deleteInvitation(invitationId: number) {
  return del<ApiResponse<string>>(`/admin/invitations/${invitationId}`);
}

/**
 * 获取站点统计
 */
export function getAdminStats() {
  return get<ApiResponse<AdminStats>>('/admin/stats/overview');
}

/**
 * 获取流量统计
 */
export function getTrafficStats(days: number = 30, startDate?: string, endDate?: string) {
  const params: any = { days };
  if (startDate) params.startDate = startDate;
  if (endDate) params.endDate = endDate;
  return get<ApiResponse<{ dailyStats: { date: string; upload: number; download: number }[] }>>('/admin/stats/traffic', params);
}

/**
 * 获取活跃用户统计
 */
export function getActiveUsersStats(days: number = 30, startDate?: string, endDate?: string) {
  const params: any = { days };
  if (startDate) params.startDate = startDate;
  if (endDate) params.endDate = endDate;
  return get<ApiResponse<{ activeUsers: { date: string; activeUsers: number; newUsers: number }[] }>>('/admin/stats/active-users', params);
}

export const updateUser = async (user: User): Promise<void> => {
    return request.put(`/api/admin/users/${user.id}`, user);
};

/**
 * 删除用户
 */
export function deleteUser(userId: number) {
    return del<ApiResponse<null>>(`/admin/users/${userId}`);
} 